//边缘触发事件特性
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <errno.h>

#define BUF_SIZE 4
#define EPOLL_SIZE 50

void setnonblockingmode(int fd);
void error_handling(char* message);

int main(int argc, char* argv[])
{
    //socket相关
    int serv_sock, clnt_sock;
    struct sockaddr_in serv_adr, clnt_adr;
    socklen_t adr_sz;

    //epoll相关
    struct epoll_event* ep_events;
    struct epoll_event event;
    int epfd, event_cnt;

    //buf相关
    int str_len, i;
    char buf[BUF_SIZE];

    if(argc != 2)
    {
        printf("Usage : %s <port> \n", argv[0]);
        exit(1);
    }

    serv_sock = socket(PF_INET, SOCK_STREAM, 0);

    memset(&serv_adr, 0, sizeof(serv_adr));
    serv_adr.sin_family = AF_INET;
    serv_adr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_adr.sin_port = htons(atoi(argv[1]));

    if(bind(serv_sock, (struct sockaddr*)&serv_adr, sizeof(serv_adr))== -1)
        error_handling("bind() error\n");

    if(listen(serv_sock, 5) == -1)
        error_handling("listen() error\n");

    //将服务端套接字设置为非阻塞模式
    setnonblockingmode(serv_sock);

    //创建保存epoll文件描述符的空间
    epfd = epoll_create(EPOLL_SIZE);
    //将发生事件的文件描述符集中在一起的集合
    ep_events = malloc(sizeof(struct epoll_event) * EPOLL_SIZE);

    //注册服务端套接字文件描述符读（处理连接请求）事件
    event.events = EPOLLIN;
    event.data.fd = serv_sock;
    epoll_ctl(epfd, EPOLL_CTL_ADD, serv_sock, &event);

    while(1)
    {
        event_cnt = epoll_wait(epfd, ep_events, EPOLL_SIZE, -1);//成功时返回发生事件的文件描述符数，否则-1
        if(event_cnt == -1)
        {
            puts("epoll wait() error \n");
            break;
        }
        printf("return wait \n");
        for(i = 0; i < event_cnt; i++)
        {
            if(ep_events[i].data.fd == serv_sock)//处理连接请求
            {
                adr_sz = sizeof(clnt_adr);
                clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_adr, &adr_sz);
                if(clnt_sock == -1)
                {
                    printf("accept error \n");
                    continue;
                }
                //将与客户端连接的套接字设置为非阻塞模式
                setnonblockingmode(clnt_sock);
                //将与客户端连接的套接字注册
                event.events = EPOLLIN | EPOLLET;//边缘触发
                event.data.fd = clnt_sock;
                epoll_ctl(epfd, EPOLL_CTL_ADD, clnt_sock, &event);
                printf("Connected Client : %d \n", clnt_sock);
            }
            else//处理客户端信息，边缘触发不会重复注册事件，需要一次性读入输入缓冲区中的信息
            {
                while(1)
                {
                    str_len = read(ep_events[i].data.fd, buf, BUF_SIZE);
                    if(str_len == 0)//关闭连接
                    {
                        epoll_ctl(epfd, EPOLL_CTL_DEL, ep_events[i].data.fd, NULL);
                        close(ep_events[i].data.fd);
                        printf("Closed Client :%d \n", ep_events[i].data.fd);
                        break;
                    }
                    else if(str_len < 0)//read函数发现输入缓冲中没有可读数据时返回-1，同时在errno中保存EAGAIN常量
                    {
                        if(errno == EAGAIN)
                            break;
                    }
                    else//回声
                    {
                        write(ep_events[i].data.fd, buf, str_len);
                    }
                }
            }
        }
    }
    close(serv_sock);
    close(epfd);
    return 0;
}

void setnonblockingmode(int fd)
{
    int flag = fcntl(fd, F_GETFL, 0);
    fcntl(fd, F_SETFL, flag | O_NONBLOCK);
}

void error_handling(char* message)
{
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(-1);
}

